package com.dabai.qrtools.ui;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.dabai.qrtools.R;
import com.dabai.qrtools.dialog.MdcDialog;
import com.dabai.qrtools.other.ImageUtils;
import com.dabai.qrtools.qrcode.QRCodeUtils;
import com.dabai.qrtools.utils.AESUtils;
import com.dabai.qrtools.utils.Base64;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.dabai.qrtools.utils.ViewUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.chip.Chip;
import com.google.android.material.textfield.TextInputLayout;

import java.util.Objects;

public class GenerateActivity extends AppCompatActivity {


    private Context context;


    private MaterialToolbar mToolbar;
    private TextInputLayout mTil1;
    private Button mAddhistory;
    private ImageView mImg;
    private Chip mChipgroup1chip1;
    private Chip mChipgroup1chip2;
    private Chip mChipgroup2chip1;
    private Chip mChipgroup2chip2;
    private Chip mChipgroup1chip3;

    private SQLiteDatabase db;
    private String qrContent="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generate);
        initViews();

        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        //数据库创建与初始化
        db = openOrCreateDatabase("HistoricalRecord", Context.MODE_PRIVATE, null);
        String create = "create table if not exists GenerateHistoricalRecord(id integer primary key autoincrement,content text not null unique);";
        db.execSQL(create);

        initListenerEvent();

        Intent intent = getIntent();
        if (intent != null) {
            String incomingText = intent.getStringExtra("incomingText");
            if (incomingText != null) {
                ViewUtils.setTextInputLayoutText(mTil1, incomingText);
            }
        }

    }

    private void initListenerEvent() {

        //编辑框变动生成二维码
        mTil1.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                qrContent = ViewUtils.getTextInputLayoutText(mTil1);
                generateQr(qrContent);

            }
        });

        mImg.setOnClickListener(v -> {

            if (qrContent.isEmpty()){
                return;
            }

            ImageUtils.showBigImage(context,
                    QRCodeUtils.createSimpleQrCodeBitmap(context,qrContent
                            ,1000
            ));
        });

        //base
        mChipgroup1chip1.setOnClickListener(view -> {

            String text = ViewUtils.getTextInputLayoutText(mTil1);
            qrContent = Base64.encode(text);
            generateQr(qrContent);

        });


        //aes
        mChipgroup1chip2.setOnClickListener(view -> {

            if (ViewUtils.getTextInputLayoutText(mTil1).isEmpty()) {
                DabaiUtils.showToast(context, "生成失败:内容为空");
                return;
            }

            MdcDialog.showInputDialog(context, "AES加密", "", "请输入密码"
                    , new MdcDialog.OnInputDialogButtonListener() {
                        @Override
                        public void confirm(DialogInterface dialog, String content) {
                            if (!content.isEmpty()) {
                                String text = ViewUtils.getTextInputLayoutText(mTil1);
                                qrContent = AESUtils.encrypt(text, content);
                                generateQr(qrContent);
                                dialog.dismiss();
                            }
                        }

                        @Override
                        public void start(DialogInterface dialog, TextInputLayout textInputLayout) {
                            textInputLayout.getEditText().setFilters(new InputFilter[] {
                                    //只能输入字母和数字
                                    DigitsKeyListener.getInstance("1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") });
                        }

                        @Override
                        public void cancel() {
                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

        });

        //还原
        mChipgroup1chip3.setOnClickListener(v -> {
            String text = ViewUtils.getTextInputLayoutText(mTil1);
            generateQr(text);
        });


        //保存
        mChipgroup2chip1.setOnClickListener(view -> {

           QRCodeUtils.saveQrImageToDCIM(context,ViewUtils.getTextInputLayoutText(mTil1));

        });

        //复制
        mChipgroup2chip2.setOnClickListener(view -> {

            String text = ViewUtils.getTextInputLayoutText(mTil1);

            if (text.isEmpty()) {
                DabaiUtils.showToast(context, "复制失败:内容为空");
                return;
            }

            DabaiUtils.copyText(context, text);

        });

        mAddhistory.setOnClickListener(v -> {

            if (ViewUtils.getTextInputLayoutText(mTil1).isEmpty()){
                return;
            }

            ContentValues in = new ContentValues();
            in.put("content", ViewUtils.getTextInputLayoutText(mTil1));
            db.insert("GenerateHistoricalRecord", null, in);
            DabaiUtils.showToast(context,"已添加");

            if (DabaiUtils.isFunctionFirstOpen(context,"addHistory")){
                DabaiUtils.showDialog(context, "在主页，长按\"二维码生成\"按钮查看历史记录");
            }

        });

        //解决滑动冲突
        ViewUtils.FixScrollViewConflict(mTil1.getEditText());

    }

    /**
     * 生成qr
     *
     * @param text 文本
     */
    private void generateQr(String text) {

        if (text.isEmpty()) {
            return;
        }

        QRCodeUtils.setImageView(context,mImg,text);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mTil1 = findViewById(R.id.til1);
        mAddhistory = findViewById(R.id.addHistory);
        mImg = findViewById(R.id.img);

        mChipgroup1chip1 = findViewById(R.id.chipGroup1Chip1);
        mChipgroup1chip2 = findViewById(R.id.chipGroup1Chip2);
        mChipgroup2chip1 = findViewById(R.id.chipGroup2Chip1);
        mChipgroup2chip2 = findViewById(R.id.chipGroup2Chip2);
        mChipgroup1chip3 = findViewById(R.id.chipGroup1Chip3);
    }
}